<script lang="ts" setup>
import router from '@/router'
import { reactive, ref } from 'vue'
import type { FormState } from '@/common/types/user-type'
import { useUserStore } from '@/common/stores/users-store'
import { getUserPhoneApi } from '@/common/apis/user'

const formRef = ref()
const userStore = useUserStore()
const formState = reactive<FormState>({
  mobile: '13800000002',
  password: 'hm#qd@23!',
  remember: [],
})

const rules = {
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'change' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号码必须以1开头,并且满11位的号码',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 8, message: '密码至少为 8 位字符', trigger: 'blur' },
    {
      pattern: /^[^, ]+$/,
      message: '密码不允许包含空格或逗号',
      trigger: 'blur',
    },
  ],
  remember: [
    {
      type: 'array',
      required: true,
      message: '请勾选用户协议',
      trigger: 'change',
    },
  ],
}

const onsubmit = async () => {
  await formRef.value.validate()
  const response = await getUserPhoneApi(formState.mobile, formState.password)
  console.log(response, '获取token')
  // 合并两个数据并存储到 userStore 的 userInfo 中
  userStore.userInfo = {
    ...formState,
    ...response.data,
    token: response.data.data,
  }

  router.push('/home')
}
</script>

<template>
  <div class="phone">
    <h1>手机号登录</h1>
    <a-form :model="formState" :rules="rules" class="phone-form" ref="formRef" autocomplete="off">
      <a-form-item name="mobile" ref="mobile">
        <a-input
          class="phone-form-input"
          placeholder="请输入手机号码"
          v-model:value="formState.mobile"
        />
      </a-form-item>

      <a-form-item name="password" ref="password">
        <a-input-password
          class="phone-form-input"
          placeholder="请输入密码"
          v-model:value="formState.password"
        />
      </a-form-item>

      <a-form-item name="remember" ref="remember">
        <a-checkbox-group v-model:value="formState.remember">
          <a-checkbox>用户平台使用协议</a-checkbox>
        </a-checkbox-group>
      </a-form-item>

      <a-form-item>
        <a-button class="phone-form-button" type="primary" @click="onsubmit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style lang="scss" scoped>
.phone {
  &-form {
    margin-top: 40px;
    &-input {
      height: 45px;
    }
    &-button {
      width: 100%;
      height: 40px;
    }
  }
}
</style>
